package com.tianqu.tms.www.transfer.controller;

import java.util.ArrayList;
import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.util.car.TmsCarModelInfoApi;
import com.tianqu.tms.dao.TmsDao;
import com.tianqu.tms.dao.TransferProcessHistoryDao;
import com.tianqu.tms.dao.TransferProcessHistoryDaoImp;
import com.tianqu.tms.dto.BaseCarInfoDto;
import com.tianqu.tms.dto.MarketCarInfoDto;
import com.tianqu.tms.dto.TransferAcceptedInfoDto;
import com.tianqu.tms.dto.TransferProcessHistoryDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.CarStyle;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.www.transfer.actionform.PublicSecurityAuditActionForm;
import com.tianqu.tms.www.transfer.actionform.TransferRgActionForm;
import com.tianqu.tms.www.transfer.viewhelper.PublicSecurityAuditInputViewHelper;

public class PublicSecurityAuditInputController extends TmsController {
	private Logger logger = Logger.getLogger(PublicSecurityAuditInputController.class);

	@SuppressWarnings("unchecked")
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = getTxController();
		try {
			controller.begin();
			Codes code = Codes.getInstance();
			TransferAcceptedInfo acceptedInfo = TransferAcceptedInfo.getInstance();
			List<String> serialList = new ArrayList<String>();
			List<TransferAcceptedInfo> transferAcceptedInfoList = new ArrayList<TransferAcceptedInfo>();
			PublicSecurityAuditInputViewHelper viewHelper = new PublicSecurityAuditInputViewHelper();
			String strGroup = (String)uc.getAttribute("group");
			uc.removeAttribute("group");
			
			if (StringUtil.isNullOrBlank(strGroup)) {
				// 点击查询进行审核
				PublicSecurityAuditActionForm inputForm = (PublicSecurityAuditActionForm)uc.getInputForm();
				String serial = inputForm.getSerial();
				viewHelper.setSerial(serial);
				transferAcceptedInfoList = acceptedInfo.findListBySerial(serial);
				
				List<TransferAcceptedInfo> transferAcceptedInfoListtmp = new ArrayList<TransferAcceptedInfo>();
				for (int i = 0; i < transferAcceptedInfoList.size(); i++) {
					TransferAcceptedInfo transferAcceptedInfo = transferAcceptedInfoList.get(i);
					int transferType = transferAcceptedInfo.getTransferType();
					if (transferType == 2 || transferType == 3 || transferType == 5) {
						if (StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages1())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages2())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages3())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages4())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages6())) {

							transferAcceptedInfoListtmp.add(transferAcceptedInfo);
						}
					}
					
					if (transferType == 1 || transferType == 4) {
						if (StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages6())) {
							
							transferAcceptedInfoListtmp.add(transferAcceptedInfo);
						}
					}
					
					if (transferType == 6) {
						if (StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages1())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages2())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages3())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages4())) {
							transferAcceptedInfoListtmp.add(transferAcceptedInfo);
						}
					}
					
					if (transferType == 7) {
						if (StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages1())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages2())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages4())
								&& StringUtil.isNotBlank(transferAcceptedInfo.getMaterialImages8())) {
							transferAcceptedInfoListtmp.add(transferAcceptedInfo);
						}
					}
				}

				transferAcceptedInfoList = transferAcceptedInfoListtmp;
				
			} else {
				// 点击分组进行审核
				// 到系统功能配置表（tms_configure）获取参数名为gashGroup的值,确定分组
				String strGashGroup = Registry.getConfig(TmsConstants.GASH_GROUP);
				String[] gashGroup = strGashGroup.split("\\]\\[");

				int group = 0;
				if (strGroup.equals("A")) group = 0;
				if (strGroup.equals("B")) group = 1;
				if (strGroup.equals("C")) group = 2;
					
				serialList = acceptedInfo.findListBySerial(gashGroup[group].replaceAll("\\[", "").replaceAll("\\]", "").split(","));
				
				if (serialList != null && serialList.size() > 0) {
					String serial = serialList.get(0);
					transferAcceptedInfoList = acceptedInfo.findListBySerial(serial);
				}
			}
			
			if (transferAcceptedInfoList == null || transferAcceptedInfoList.size() == 0) {
				// 0件 页面提示“【U0039】查询的结果不存在。
				uc.setAttribute("auditErr", "U0039");
			} else if (transferAcceptedInfoList != null && transferAcceptedInfoList.size() > 1) {
				// 复数件 页面提示“【U1405】出现重复流水号业务，请联系系统管理员。
				uc.setAttribute("auditErr", "U1405");
			} else {
				// 1件
				TransferAcceptedInfo transferAcceptedInfo = transferAcceptedInfoList.get(0);
				int transferRegister = transferAcceptedInfo.getTransferRegister();
				if (transferRegister == 1) {
					// 如果有符合条件数据 并且 公安审核（transferRegister）为“1：公安审核通过”，那么页面提示“【U1068】该业务已通过公安网审核，不能重复受理。”
					uc.setAttribute("auditErr", "U1068");
				} else {
					
					//分组信息及待处理的信息条数。
					// 到系统功能配置表（tms_configure）获取参数名为gashGroup的值,确定分组
					String strGashGroup = Registry.getConfig(TmsConstants.GASH_GROUP);
					String[] gashGroup = strGashGroup.split("\\]\\[");

					String linkContent = "";
					if (gashGroup != null && gashGroup.length > 0) {
						for (int i = 0; i < gashGroup.length; i++) {
							
							if (gashGroup[i].indexOf(transferAcceptedInfo.getSerial().substring(transferAcceptedInfo.getSerial().length() - 1)) > 0) {
								
								List<String> serialGroupList = acceptedInfo.findListBySerial(gashGroup[i].replaceAll("\\[", "").replaceAll("\\]", "").split(","));
								
								if (i == 0) linkContent = "A组：流水号尾号是";
								if (i == 1) linkContent = "B组：流水号尾号是";
								if (i == 2)	linkContent = "C组：流水号尾号是";
								
								linkContent = linkContent + gashGroup[i].replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(",", "，")
												+ "的信息（待处理" + serialGroupList.size()+ "笔）";
							}
						}
					}
					
					viewHelper.setLinkContent(linkContent);
					viewHelper.setSerial(transferAcceptedInfo.getSerial());
					viewHelper.setVin(transferAcceptedInfo.getVin());
					viewHelper.setLicensePlate(transferAcceptedInfo.getLicensePlate());
					viewHelper.setMemberId(transferAcceptedInfo.getMemberId());
					viewHelper.setAttnId(transferAcceptedInfo.getAttnId());
					viewHelper.setTransferType(transferAcceptedInfo.getTransferType());
					viewHelper.setTransferTypeName(code.getItemValueByItemIdAndItemCode(Codes.TRANSFER_TYPE, transferAcceptedInfo.getTransferType()));
					if (!StringUtil.isNullOrBlank(transferAcceptedInfo.getShiftToLevel())) 
						viewHelper.setShiftToLevel("（现行转入要求：" + transferAcceptedInfo.getShiftToLevel() + "）");
					viewHelper.setCarMarketInProv(transferAcceptedInfo.getCarMarketInProv());
					viewHelper.setCarMarketInCity(transferAcceptedInfo.getCarMarketInCity());
					viewHelper.setMaterialImages1(transferAcceptedInfo.getMaterialImages1());
					viewHelper.setMaterialImages2(transferAcceptedInfo.getMaterialImages2());
					viewHelper.setMaterialImages3(transferAcceptedInfo.getMaterialImages3());
					viewHelper.setMaterialImages4(transferAcceptedInfo.getMaterialImages4());
					viewHelper.setMaterialImages5(transferAcceptedInfo.getMaterialImages5());
					viewHelper.setMaterialImages6(transferAcceptedInfo.getMaterialImages6());
					viewHelper.setMaterialImages7(transferAcceptedInfo.getMaterialImages7());
					viewHelper.setMaterialImages8(transferAcceptedInfo.getMaterialImages8());
					viewHelper.setMaterialImages9(transferAcceptedInfo.getMaterialImages9());
					viewHelper.setMaterialImages10(transferAcceptedInfo.getMaterialImages10());
					viewHelper.setProName(transferAcceptedInfo.getProName());
					viewHelper.setCityName(transferAcceptedInfo.getCityName());
					viewHelper.setStatus(transferAcceptedInfo.getStatus());
					viewHelper.setEpStandard(transferAcceptedInfo.getEpStandard());// 环保达标
					viewHelper.setCarReplaceType(transferAcceptedInfo.getCarReplaceType());// 客车换型
					viewHelper.setCarPeccancy(transferAcceptedInfo.getCarPeccancy());// 车辆违章
					viewHelper.setOverdue(transferAcceptedInfo.getOverdue());// 超检审核
					viewHelper.setMortgage(transferAcceptedInfo.getMortgage());// 抵押审核
					viewHelper.setSealup(transferAcceptedInfo.getSealup());// 查封审核
					viewHelper.setRegistration(transferAcceptedInfo.getRegistration());// 登记证书
					viewHelper.setDrivingLicense(transferAcceptedInfo.getDrivingLicense());// 行驶证
					viewHelper.setScrapOverdue(transferAcceptedInfo.getScrapOverdue());// 报废超期
					viewHelper.setRobbery(transferAcceptedInfo.getRobbery());// 盗抢审核
					viewHelper.setPsRemark(transferAcceptedInfo.getPsRemark());// 公安审核备注
					viewHelper.setOwnerEscaping(transferAcceptedInfo.getOwnerEscaping());// 原车主在逃
					viewHelper.setOwnerScrap(transferAcceptedInfo.getOwnerScrap());// 原车主报废车
					viewHelper.setNewEscaping(transferAcceptedInfo.getNewEscaping());// 新车主在逃
					viewHelper.setNewScrap(transferAcceptedInfo.getNewScrap());// 新车主报废车
					viewHelper.setNewLive(transferAcceptedInfo.getNewLive());// 新车主居住证
					TransferProcessHistoryDao uDao = (TransferProcessHistoryDao) TmsDao.getInstance(TmsDao.TMS_TRANSFER_PROCESS_HISTORY);
					List<TransferProcessHistoryDto> tList = uDao.loadTransferProcessHistoryBySerial(transferAcceptedInfo.getSerial());
					if(tList != null && tList.size() > 0) {
						viewHelper.setReason(tList.get(0).getReason());
					} else {
						viewHelper.setReason("");
					}
					
				}
			}
			
			uc.setAttribute(TmsConstants.VIEWHELP, viewHelper);

			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}
		logger.debug(this.getClass().getName() + "#execute was completed.");

	}
}
